package com.mgg.goods.consumer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mgg.common.consumer.MessageConsumer;
import com.mgg.common.messaging.GoodsQtyChangeProcessor;
import com.mgg.common.payload.GoodsQtyChangePayload;
import com.mgg.common.util.JsonUtils;
import com.mgg.common.vo.PageData;
import com.mgg.goods.service.stock.StockService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;

@Component
public class GoodsQtyReduceMessageConsumer implements MessageConsumer<GoodsQtyChangePayload> {

	Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private StockService stockService;
	
    @StreamListener(GoodsQtyChangeProcessor.INPUT)
	@Override
	public void receiveMessage(GoodsQtyChangePayload payload) {
    	log.info("MQ【修改商品库存】	payload = {}", JsonUtils.toJson(payload));
    	String orderId = payload.getOrderId();
    	String operate = payload.getOperate();
    	List<PageData> skuList = payload.getSkuList();
    	try {
    		List<Map<String,Object>> list = new ArrayList<>();
    		for (PageData sku : skuList) {
    			Map<String,Object> map = new HashMap<>();
    			map.put("spec_id", sku.get("spec_id"));
    			map.put("num", sku.get("goods_count"));
    			list.add(map);
    		}
    		stockService.changeGoodsInvByOrder(list,operate,orderId);   		    			
		} catch (Exception e) {
			log.error("订单修改库存失败");
			log.error(e.getMessage(), e);
		}
	}
}
